package greentea.webloginmodule.servlets;

import greentea.webloginmodule.jaas.LoginUtil;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author LFilipkiewicz
 * 
 */
public class LoginHandler extends HttpServlet {

	/** */
	private static final long serialVersionUID = 1L;

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());

	/**
	 * 
	 */
	protected static LoginUtil loginUtil = null;

	// TODO move it to ServletContext
	public static final String LOGIN_FORM_FIELD = "userLogin";
	public static final String PASSWORD_FORM_FIELD = "userPassword";
	public static final String IS_LOGGED_IN = "logon.isDone";
	public static final String TARGET_PAGE = "targetPage";

	// filled while Servlet init() from ServletContext
	public static String LOGIN_PAGE;
	public static String ERROR_PAGE;
	public static String HOME_PAGE;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		this.doPost(req, res);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// Get the user's name and password
		String userLogin = req.getParameter(LOGIN_FORM_FIELD);
		String userPassword = req.getParameter(PASSWORD_FORM_FIELD);
		// check if the userLogin and userPassword are provided
		// (unauthorized servlet call)
		if (userLogin == null || userPassword == null) {
			res.sendRedirect(LoginHandler.LOGIN_PAGE);
			return;
		}
		if (isLogonDone(req, res)) {
			logger.info("Session already created and user ["
					+ req.getSession().getAttribute(LoginHandler.IS_LOGGED_IN)
					+ "] already logged in");
			req.getRequestDispatcher(LoginHandler.HOME_PAGE).forward(req, res);
			return;
		}
		// Check the name and password for validity
		if (!loginUser(userLogin, userPassword)) {
			// invalidate the session, cause it is not needed
			req.getSession().invalidate();
			// user cannot be logged in; redirect directly to LOGIN_PAGE
			res.sendRedirect(LoginHandler.ERROR_PAGE);
			return;
		} else {
			// Create the session if not already created
			HttpSession session = req.getSession(true);
			// set the name of the user as his login in the session
			session.setAttribute(LoginHandler.IS_LOGGED_IN, userLogin);
			logger.info("User [" + userLogin + "] logged in. Session ID:"
					+ session.getId());
			res.sendRedirect(LoginHandler.HOME_PAGE);
//			req.getRequestDispatcher(LoginHandler.HOME_PAGE).forward(req, res);
		}
	}

	/**
	 * Login user procedure. Login is based on mdb.remote JAAS
	 * 
	 * @param userLogin
	 * @param userPassword
	 * @return
	 */
	protected boolean loginUser(String userLogin, String userPassword) {
		// by default - trust no one.
		boolean retVal = false;
		logger.debug("Authorization started...");
		LoginHandler.loginUtil = new LoginUtil();
		retVal = loginUtil.loginUser(userLogin, userPassword);
		logger.debug("Authorization finished [" + retVal + "]");
		return retVal;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#init()
	 */
	public void init() {
		// get the parameters from ServletContext
		ServletContext ctx = getServletConfig().getServletContext();
		LoginHandler.HOME_PAGE = (String) ctx.getInitParameter("HOME_PAGE");
		LoginHandler.LOGIN_PAGE = (String) ctx.getInitParameter("LOGIN_PAGE");
		LoginHandler.ERROR_PAGE = (String) ctx.getInitParameter("ERROR_PAGE");
		
		// TODO make home page and error page as HTTP requests
	}

	/**
	 * Inform if the current session is already logged in. Method checks the
	 * session parameter IS_LOGGED_IN if exists and if yes return true.
	 * 
	 * @param req
	 *            to operate with session parameters
	 * @param res
	 *            HttpServletResponse
	 * @return true - if session is logon, false - if not
	 */
	public static Boolean isLogonDone(HttpServletRequest req,
			HttpServletResponse res) {
		Boolean retVal = false;
		HttpSession session = req.getSession(false);
		if (session != null
				&& session.getAttribute(LoginHandler.IS_LOGGED_IN) != null) {
			retVal = true;
		}
		return retVal;
	}
}